# -*- coding: UTF-8 -*-
import re
from urllib.parse import urlparse

from zc_core.util.http_util import fill_link

"""
常见电商平台商品编码解析规则
"""
pattern_list = {
    # 得力
    'b2b.nbdeli.com': [re.compile(r'nbdeli\..*/Goods/ItemDetail_(.+)_')],
    # 史泰博
    'www.staples.cn': [re.compile(r'staples\..*/product/(.+)')],
    # 京东
    'item.jd.com': [re.compile(r'jd\.\w+/(.+)\.htm.*')],
    # 京东MRO
    'i-item.jd.com': [re.compile(r'jd\.\w+/(.+)\.htm.*')],
    # 京东国际
    'item.jd.hk': [re.compile(r'jd\.\w+/(.+)\.htm.*')],
    # 苏宁
    'product.suning.com': [re.compile(r'suning\..*/\d+/(.+)\..*')],
    # 齐心
    'www.comix.com.cn': [re.compile(r'.comix\..*/(.+)\..*')],
    # 领先未来
    'www.66123123.com': [re.compile(r'66123123\..*/Goods/GoodsDetail\?.*id=(.+).*')],
    # 晨光
    'www.colipu.com': [re.compile(r'colipu\..*/itemcode-(.+)\..*'),
                       re.compile(r'colipu\..*/search\.html\?q=(.+)')],
    # 浙江物产
    'www.zjmi-mall.com': [re.compile(r'zjmi-mall\..*\?.*goods_code=(.+)&.*')],
    # 办公伙伴
    'www.officemate.cn': [re.compile(r'officemate\..*/product-(.+)\..*')],
    # 锐祺达
    'www.rqd-office.com': [re.compile(r'rqd-office\..*\?.*?id=(.+)&*')],
}


def parse_sp_sku_id(url, err=''):
    """
    通用编码解析器
    :param url:
    :param err:
    :return:
    """
    try:
        if url:
            url = fill_link(url)
        host = urlparse(url).hostname
        if host:
            ptn_list = pattern_list.get(host)
            if ptn_list:
                for ptn in ptn_list:
                    arr = ptn.findall(url.strip())
                    if len(arr):
                        return arr[0].strip()

        return ''
    except Exception:
        return err


def convert_id2code(plat_code, sp_sku_id):
    """
    供应商商品编号构造
    :param plat_code:
    :param sp_sku_id:
    :return:
    """
    if plat_code and sp_sku_id:
        if plat_code == 'deli':
            return sp_sku_id.replace('PCS', '').replace('CAR', '').replace('BX1', '')

    return sp_sku_id


# 测试
if __name__ == '__main__':
    # print(parse_sp_sku_id('http://www.rqd-office.com/goods.php?id=511'))
    # print(parse_sp_sku_id('https://item.jd.com/100006603070.html'))
    # print(parse_sp_sku_id('https://www.comix.com.cn/3005912.html'))
    # print(parse_sp_sku_id('http://b2b.nbdeli.com/Goods/ItemDetail_101128094_EC.htm'))
    # print(parse_sp_sku_id('http://www.staples.cn/product/1100006582EA'))
    # print(parse_sp_sku_id('www.colipu.com//itemcode-WL5079.html'))
    # print(parse_sp_sku_id('河南'))
    print(parse_sp_sku_id('http://www.colipu.com/search.html?q=188022'))
    pass
